import { reqGetCode, reqUserInfo, reqUserLogin, reqUserRegister, reqLogout } from "@/api";
import { setToken, getToken, removeToken } from '@/utils/token'
const state = {
  code: '',
  token: getToken(),
  userInfo: {}
};
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  LOGOUT(state) {
    state.token = '';
    state.userInfo = '';
    removeToken();
  }
};

const actions = {
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    // console.log(result);
    if (result.code == 200) {
      commit('GETCODE', result.data)
      return 'ok'
    } else
      return Promise.reject(new Error('faile'))
  },

  async userRegister({ commit }, user) {
    let result = await reqUserRegister(user)
    // console.log(result);
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userLogin({ commit }, data) {
    let result = await reqUserLogin(data);
    // console.log(result);
    // console.log(data);

    if (result.code == 200) {
      commit('USERLOGIN', result.data.token)
      // localStorage.setItem('TOKEN', result.data.token);
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }

  },
  async getUserInfo({ commit }) {
    let result = await reqUserInfo();
    // console.log(result.code);
    // console.log(result);

    if (result.code == 200) {
      commit('GETUSERINFO', result.data);
      return 'ok';
    } else {
      return Promise.reject(new Error('faile'));
    }

  },
  async Logout({ commit }) {
    let result = await reqLogout();
    if (result.code == 200) {
      commit('LOGOUT');
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  }
};
const getters = {

};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}